<?php

namespace App\Ship\Phones;

use App\Ship\Parents\Phones\Phone;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Support\Str;

class SmsRu extends Phone
{
    protected Client $client;

    protected string $from;

    protected array $to;
    protected string $text;

    public function __construct(string $text)
    {
        $this->text = $text;
        $this->client = new Client();
        $this->from = config('phone.smsru.from');
    }

    public static function create(string $text): static
    {
        return new static($text);
    }

    public function from(string $from): static
    {
        $this->from = $from;

        return $this;
    }

    public function loadFrom(): string
    {
        return $this->from;
    }

    public function to(string ...$to): static
    {
        $to = is_array($to) ? $to : func_get_args();

        foreach ($to as $item) {
            $this->to[] = Str::replaceFirst('+', '', $item);
        }

        return $this;
    }

    public function send(): bool
    {
        $response = $this->client->get(config('phone.smsru.sms_url') . '?' . $this->payload());

        return $this->parseResult($response->getBody()->getContents());
    }

    protected function payload(): string
    {
        return 'login=' . config('phone.smsru.username') .
            '&psw=' . config('phone.smsru.password') .
            '&phones=' . implode(',', $this->to) .
            '&mes=' . urlencode(iconv("windows-1251", "utf-8", $this->text)) .
            '&sender=' . $this->from;
    }

    protected function parseResult(string $result): bool
    {
        if (str_contains($result, 'OK')) {
            return true;
        } elseif (str_contains($result, 'ERROR')) {
            throw new Exception($result);
        }

        throw new Exception('Не удалось распознать ответ от сервиса');
    }
}
